package org.shezhua.android.i18n;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.eclipse.ui.console.MessageConsoleStream;
import org.shezhua.android.i18n.model.ResString;

public class AndroidResStringWriter {
	private MessageConsoleStream consoleStream;

	public AndroidResStringWriter(MessageConsoleStream consoleStream) {
		this.consoleStream = consoleStream;
	}

	public int write(Map<File, Map<String, ResString>> modifiedData) {
		SAXReader reader = new SAXReader();
		reader.setEncoding("UTF-8");
		reader.setValidation(false);
		int count = 0;
		Set<Entry<File, Map<String, ResString>>> set = modifiedData.entrySet();
		for (Entry<File, Map<String, ResString>> entry : set) {
			File file = entry.getKey();
			Map<String, ResString> value = entry.getValue();
			
			Document doc = null;
			boolean modified = false;
			try {
				doc = reader.read(file);
				
				Element root = doc.getRootElement();
				if(!"resources".equals(root.getName())) {
					continue;
				}
				Iterator it = root.elementIterator();
				while(it.hasNext()) {
					Element e = (Element) it.next();
					if("string".equals(e.getName())) {
						String key = e.attributeValue("name");
						if(value.containsKey(key)) {
							consoleStream.println("Writed: " + file + ", " + key);
							modified = true;
							count++;
							
							ResString resString = value.get(key);
							e.setText(resString.getValue());
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace(new PrintStream(consoleStream));
			} finally {
				if(modified && doc != null) {
					write(doc, file);
				}
				doc = null;
				modified = false;
			}
		}
		return count;
	}
	
	void write(Document doc, File file) {
		try {
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("utf-8");
			XMLWriter output = new XMLWriter(new FileOutputStream(file), format);
			output.write(doc);
			output.close();
		} catch (IOException e) {
			e.printStackTrace(new PrintStream(consoleStream));
		}
	}
}
